<?php
include ('../inicio/conectarse.php');

session_start();

	//Function to sanitize values received from the form. Prevents SQL injection
	function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}
	
	//Sanitize the POST values
	$nombre = clean($_POST['nombre']);
	$descripcion = clean($_POST['descripcion']);
	
	if($_SESSION['UPDATE']=0){
		//Check for duplicate tipoMateriaPrima Nombre
		if($login != '') {
			$qry = "SELECT * FROM categorias WHERE nombre='$nombre'";
			$result = mysql_query($qry);
			if($result) {
				if(mysql_num_rows($result) > 0) {
					$errmsg_arr[] = 'Esta categoria ya fue creada. Error!';
					$errflag = true;
				}
				@mysql_free_result($result);
			}
			else {
				die("Query failed");
			}
		}
		
		//If there are input validations, redirect back to the registration form
		if($errflag) {
			$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
			session_write_close();
			header("location: categorias-form.php");
			exit();
		}
		
		//Create INSERT query
		$qry = "INSERT INTO categorias(nombre, descripcion) VALUES('$nombre','$descripcion')";
	
		$result = mysql_query($qry);
	
		//Check whether the query was successful or not
		if($result) {
			header("location: ../../paginas/admin/index.php");
			exit();
		}else {
			die("Query failed");
		}
	}else{	
		$id=$_SESSION['ID'];
		$qry = "UPDATE categorias SET nombre = '$nombre', descripcion = '$descripcion' WHERE ID_CATEGORIAS=".$id;
	
		$result = mysql_query($qry);
	
		//Check whether the query was successful or not
		if($result) {
			header("location: ../../paginas/admin/index.php");
			exit();
		}else {
			die("Query failed");
		}
	}
?>